package grupobbva.pe.operhc.action;

import grupobbva.pe.operhc.domain.PerfilRol;
import grupobbva.pe.operhc.domain.SegUsuario;
import grupobbva.pe.operhc.domain.Tabla;
import grupobbva.pe.operhc.form.PerfilRolForm;
import grupobbva.pe.operhc.service.ParametroService;
import grupobbva.pe.operhc.service.ParametroServiceImpl;
import grupobbva.pe.operhc.util.Constant;
import grupobbva.pe.operhc.util.ReadProperties;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class PerfilRolAction extends DispatchAction {
	
	private static Logger logger = Logger.getLogger(PerfilRolAction.class);
	private ParametroService parametrosService = null;
	


	public PerfilRolAction() {
		parametrosService = new ParametroServiceImpl();
	}
	

	
	public ActionForward verFormulario(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		if(logger.isDebugEnabled()){
			logger.debug("* entrando al PerfilRol.verFormulario *");
		}
		
		//frk: validamos que el usuario se encuentre en sesion
		HttpSession session = request.getSession();
		SegUsuario usuarioSession = (SegUsuario)session.getAttribute("usuarioSession");
		
		if(logger.isDebugEnabled()){
			logger.debug("******** Objeto usuario en sesion "+usuarioSession);
		}
		
		if(usuarioSession == null){
			response.sendRedirect("loginLDAP.do?method=logout");
			return null;
		}
				
		if(!"1".equals(usuarioSession.getAdmin())){
			response.sendRedirect("operativizacion.jsp");
			return null;			
		}
		
		try{

			List<Tabla> listRolesFree = new ArrayList<Tabla>();
			List<Tabla> listRolesUsed = new ArrayList<Tabla>();
			List<Tabla> listPerfiles = parametrosService.getListPerilesLocal();
			
			List<Tabla> listRoles = parametrosService.getListRoles();
			
			PerfilRolForm perfilRolForm =(PerfilRolForm)form;			
			perfilRolForm.setCmbReasonDestinationp(new String[0]);
			perfilRolForm.setCmbReasonSourcep(new String[0]);
			//SegUsuario bean = new SegUsuario();
			
			String codigo = request.getParameter("codigo");
			perfilRolForm.setIdPerfil(codigo);
			if(StringUtils.isNotBlank(codigo)){
				
						//bean = parametrosService.getUserByCode(id, nivel);
						listRolesUsed = parametrosService.getListPerfilRoles(codigo);
						
						List<String> listCodes = new ArrayList<String>();
						if(listRolesUsed != null && !listRolesUsed.isEmpty()){
							for (Tabla rolesUsed : listRolesUsed) {
								listCodes.add(String.valueOf(rolesUsed.getIdTabla()));
							}
							
							for (Tabla rolesGeneral : listRoles) {
								if(!listCodes.contains(String.valueOf(rolesGeneral.getIdTabla()))){
									listRolesFree.add(rolesGeneral);
								}
							}
						}					
									
								
			}
			
			if(listRolesUsed == null || listRolesUsed.isEmpty()){
				listRolesFree = listRoles;
			}
			
			if(logger.isDebugEnabled()){
				if(listRolesUsed != null){
					logger.debug("* numero de roles del perfil: "+listRolesUsed.size());
				}else{
					logger.debug("* numero de roles del perfil: 0");
				}				
			}
			
			//BeanUtils.copyProperties(manteUserForm, bean);
			perfilRolForm.setPerfiles(listPerfiles);			
			
			
			request.setAttribute("listRolesFreep", listRolesFree);
			request.setAttribute("listRolesUsedp", listRolesUsed);
			request.setAttribute("back", "/adminForm.do?method=verMantenimiento");
			
			if(logger.isDebugEnabled()){
				logger.debug("* saliendo del PerfilRolAction.verFormulario *");
			}
			
			return mapping.findForward("perfilRolForm");
			
		}catch(Exception e){
			
			logger.error("Exception PerfilRolAction.verFormulario: " + e.getMessage());
			return mapping.findForward("mantenimiento");
			
		}		
	}
	
	public ActionForward guardar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
			
			if(logger.isDebugEnabled()){
				logger.debug("* entrando al PerfilRolAction.guardar *");
			}
			
			//frk: validamos que el usuario se encuentre en sesion
			HttpSession session = request.getSession();
			if(session.getAttribute("usuarioSession") == null){
				response.sendRedirect("loginLDAP.do?method=logout");
				return null;
			}
			
			ReadProperties readProperties = new ReadProperties();
			
			try{
				
				PerfilRol bean = new PerfilRol();
				PerfilRolForm perfilRolForm =(PerfilRolForm)form;

				BeanUtils.copyProperties(bean, perfilRolForm);
				String idPerfil=bean.getIdPerfil();
				parametrosService.savePerfilRol(bean);
				
				verPerfilRol(idPerfil,request,form);				
				request.setAttribute(Constant.MESSAGES_INF_KEY, readProperties.getProperty("etiqueta.success.update"));
				
			
			} catch (Exception e) {
				logger.error("Exception UsuarioAction.guardar: " + e.getMessage());
				request.setAttribute(Constant.MESSAGES_ERR_KEY, readProperties.getProperty("etiqueta.error.save"));
			}
			
			return mapping.findForward("perfilRolForm");
		}
	
	
	
	private void verPerfilRol(String idPerfil,HttpServletRequest request,ActionForm form) throws Exception {
			
	
			try{
				
				List<Tabla> listRolesFree = new ArrayList<Tabla>();
				List<Tabla> listRolesUsed = new ArrayList<Tabla>();
				//List<Tabla> listPerfiles = parametrosService.getListPerilesLocal();
				PerfilRolForm perfilRolForm =(PerfilRolForm)form;	
				perfilRolForm.setCmbReasonDestinationp(new String[0]);
				perfilRolForm.setCmbReasonSourcep(new String[0]);
				
				List<Tabla> listRoles = parametrosService.getListRoles();
				
			
				if(StringUtils.isNotBlank(idPerfil)){		
	
							listRolesUsed = parametrosService.getListPerfilRoles(idPerfil);
							
							List<String> listCodes = new ArrayList<String>();
							if(listRolesUsed != null && !listRolesUsed.isEmpty()){
								for (Tabla rolesUsed : listRolesUsed) {
									listCodes.add(String.valueOf(rolesUsed.getIdTabla()));
								}
								
								for (Tabla rolesGeneral : listRoles) {
									if(!listCodes.contains(String.valueOf(rolesGeneral.getIdTabla()))){
										listRolesFree.add(rolesGeneral);
									}
								}
							}		
				}
				
				if(listRolesUsed == null || listRolesUsed.isEmpty()){
					listRolesFree = listRoles;
				}				
				
				request.setAttribute("listRolesFreep", listRolesFree);
				request.setAttribute("listRolesUsedp", listRolesUsed);
				request.setAttribute("back", "/adminForm.do?method=verMantenimiento");				
				
			}catch(Exception e){
				logger.error("Exception UsuarioAction.verPerfilRol: " + e.getMessage());
			}		
		}
		

		public ParametroService getParametrosService() {
			return parametrosService;
		}

		public void setParametrosService(ParametroService parametrosService) {
			this.parametrosService = parametrosService;
		}


		
		

}
